import 'dart:async';

import 'package:flutter/material.dart';
import 'package:pcp/common/config/config.dart';
import 'package:pcp/main.dart';
import 'package:pcp/pages/login_page.dart';
import 'package:shared_preferences/shared_preferences.dart';

class SplashPage extends StatefulWidget {
  @override
  SplashState createState() => new SplashState();
}

class SplashState extends State<SplashPage> {
  var loginState;
  Timer _t;
  var userName;

  @override
  void initState() {
    super.initState();
    _validateLogin();
    _t = new Timer(const Duration(milliseconds: 1500), () {
      try {
        Navigator.of(context).pushAndRemoveUntil(
            PageRouteBuilder<Null>(
              pageBuilder: (BuildContext context, Animation<double> animation,
                  Animation<double> secondaryAnimation) {
                if (loginState == 0) {
                  return AnimatedBuilder(
                    animation: animation,
                    builder: (BuildContext context, Widget child) {
                      return Opacity(
                        opacity: animation.value,
                        child: new LoginPage(),
                      );
                    },
                  );
                } else {
                  return AnimatedBuilder(
                    animation: animation,
                    builder: (BuildContext context, Widget child) {
                      return Opacity(
                        opacity: animation.value,
                        child: new MainPage(userName: userName,),
                      );
                    },
                  );
                }
              },
              transitionDuration: Duration(milliseconds: 300),
            ),
            (Route route) => route == null);
      } catch (e) {}
    });
  }

  @override
  void dispose() {
    _t.cancel();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return new Material(
      color: Config.GLOBAL_COLOR,
      child: Container(
        alignment: Alignment(0, -0.3),
        child: new Text(
          "PCP",
          style: new TextStyle(
              color: Colors.white, fontSize: 50.0, fontWeight: FontWeight.bold),
        ),
      ),
    );
  }

  Future _validateLogin() async{
    Future<dynamic> future = Future(()async{
      SharedPreferences prefs = await SharedPreferences.getInstance();
      userName = prefs.getString('userName');
      return prefs.getString('userId');
    });
    future.then((val){
      if(val == null){
        setState(() {
          loginState = 0;
        });
      }else{
        setState(() {
          loginState = 1;
        });
      }
    }).catchError((_){
      print("catchError");
    });
  }
}
